package com.ruicar.afs.cloud.apply.admin.manage.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.apply.admin.manage.entity.SysAppertainRegion;
import com.ruicar.afs.cloud.apply.admin.manage.service.ApplyAppertainRegionService;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.log.annotation.SysLog;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.apply.enums.StatusEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author xudongdong
 * @date 2020-06-04
 */
@RestController
@AllArgsConstructor
@RequestMapping("/appertainRegion")
@Api(value = "appertainRegion", description = "所属区域信息")
public class ApplyAppertainRegionController {

    private final ApplyAppertainRegionService appertainRegionService;

    @PostMapping("/getByParentId/{parentId}")
    @ApiOperation(value = "通过id获取")
    public IResponse<List<SysAppertainRegion>> getByParentId(@PathVariable String parentId) {

        return new IResponse<List<SysAppertainRegion>>().setData(setInfo(appertainRegionService.list(Wrappers.<SysAppertainRegion>query().lambda()
                .eq(SysAppertainRegion::getParentId, parentId)
                .orderByAsc(SysAppertainRegion::getSortOrder))));
    }

    @PostMapping("/getAll/{ids}")
    @ApiOperation(value = "通过id获取")
    public IResponse<List<SysAppertainRegion>> getAll(@PathVariable Long[] ids) {
        List<SysAppertainRegion> appertainRegionList = setInfo(appertainRegionService.list(Wrappers.<SysAppertainRegion>query()));
        List<SysAppertainRegion> appertainRegionLists = JSONUtil.parseArray(appertainRegionList).toList(SysAppertainRegion.class);
        for (SysAppertainRegion v1 : appertainRegionLists) {
            for (Long v2 : ids) {
                if (v1.getId().equals(v2)) {
                    v1.setSelected(true);
                }
            }
        }
        Map<Long, List<SysAppertainRegion>> collect = appertainRegionLists.stream().collect(Collectors.groupingBy(SysAppertainRegion::getParentId));
        List<SysAppertainRegion> list = collect.get(0L);
        if (ObjectUtils.isNotEmpty(list)) {
            list.forEach(en -> forEach(collect, en));
        }
        return new IResponse<List<SysAppertainRegion>>().setData(list);
    }

    private static void forEach(Map<Long, List<SysAppertainRegion>> collect, SysAppertainRegion entity) {
        List<SysAppertainRegion> treeMenuNodes = collect.get(entity.getId());
        if (collect.get(entity.getId()) != null) {
            //排序
            entity.setChildren(treeMenuNodes);
            entity.getChildren().forEach(t -> {
                forEach(collect, t);
            });
        }
    }

    @PostMapping("/add")
    @ApiOperation(value = "添加")
    @SysLog("所属区域")
    @Transactional
    public IResponse<Boolean> add(@RequestBody SysAppertainRegion appertainRegion) {
        appertainRegion.setIsParent(StatusEnum.NO.getValue());
        appertainRegionService.save(appertainRegion);
        SysAppertainRegion appertainRegions = appertainRegionService.getById(appertainRegion.getParentId());
        if (appertainRegions != null && StatusEnum.NO.getValue().equals(appertainRegions.getIsParent())) {
            appertainRegions.setIsParent(StatusEnum.YES.getValue());
            appertainRegionService.updateById(appertainRegions);
        }
        return new IResponse<Boolean>().setMsg("添加成功").setData(true);
    }

    @PostMapping("/edit")
    @ApiOperation(value = "编辑")
    @SysLog("编辑所属区域")
    @Transactional
    public IResponse<Boolean> edit(@RequestBody SysAppertainRegion appertainRegion) {
        appertainRegionService.updateById(appertainRegion);
        return new IResponse<Boolean>().setMsg("编辑成功").setData(true);
    }

    @RequestMapping(value = "/delByIds/{ids}", method = RequestMethod.DELETE)
    @ApiOperation(value = "批量通过id删除")
    @SysLog("批量通过id删除所属区域")
    @Transactional
    public IResponse<Boolean> delByIds(@PathVariable String[] ids) {

        Arrays.stream(ids).forEach(id -> {
            appertainRegionService.remove(Wrappers.<SysAppertainRegion>update().lambda().eq(SysAppertainRegion::getParentId, id));
            appertainRegionService.removeById(id);
        });

        return new IResponse<Boolean>().setMsg("批量通过id删除数据成功").setData(true);
    }

    @PostMapping("/search")
    @ApiOperation(value = "区域名模糊搜索")
    public IResponse<List<SysAppertainRegion>> searchByTitle(@RequestParam String title) {
        List<SysAppertainRegion> list = appertainRegionService.list(Wrappers.<SysAppertainRegion>query().lambda().
                like(SysAppertainRegion::getTitle, title).orderByAsc(SysAppertainRegion::getSortOrder));
        list = setInfo(list);
        return new IResponse<List<SysAppertainRegion>>().setData(list);
    }

    public List<SysAppertainRegion> setInfo(List<SysAppertainRegion> list) {

        // lambda表达式
        list.forEach(item -> {
            if (!CommonConstants.PARENT_ID.equals(Long.valueOf(item.getParentId()))) {
                SysAppertainRegion parent = appertainRegionService.getById(item.getParentId());
                item.setParentTitle(parent.getTitle());
            } else {
                item.setParentTitle("一级部门");
            }
        });
        return list;
    }
}
